# -*- coding: utf-8 -*-

import os

from django.db import models
import django.utils.timezone as timezone
from django.db.models.signals import post_delete
from django.dispatch import receiver
from product.models import Chipset
from user.models import Group
from mysite import settings


CATEGORY = ( 
    ("数据手册", "数据手册"),  
    ("参考手册", "参考手册"),
    ("使用指南", "使用指南"),  
    ("入门指南", "入门指南"),
    ("应用笔记", "应用笔记"),  
    ("设计参考", "设计参考"),
    ("API参考", "API参考"),  
)


class Doctype(models.Model): 
    '''文档类型''' 
    name = models.CharField("文档类型", max_length=100)  
    display = models.BooleanField("显示", default=True)

    class Meta:
        verbose_name = "文档类型"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
  
  
class Document(models.Model):
    '''文档信息
    
    '''
    title = models.CharField("标题", max_length=100)
    display = models.BooleanField("用户可见", default=True)
    guest = models.BooleanField("访客可见", default=False)
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name="分组", blank=True, null=True)
    number = models.CharField("编号", max_length=30, null=True, blank=True)
    #category = models.CharField("类型", max_length=20, choices=CATEGORY, default="", null=True, blank=True)
    category = models.ForeignKey(Doctype, on_delete=models.CASCADE, verbose_name="类型", related_name="category", blank=True, null=True)
    chip = models.ManyToManyField(Chipset, verbose_name="芯片", default="", null=True, blank=True)  
    version = models.CharField("版本", max_length=50, null=True, blank=True)
    file = models.FileField("上传文件", upload_to='upload/doc/', null=True, blank=True, help_text="")
    #description = models.CharField("描述", max_length=200, null=True, blank=True, help_text="限200个字符")
    description = models.TextField("描述", max_length=250, null=True, blank=True, help_text="限250个字符")
    url = models.CharField("浏览URL", max_length=200, null=True, blank=True)
    #date = models.DateTimeField("发布日期", auto_now_add=True)
    date = models.DateTimeField("发布日期", default=timezone.now)

    class Meta:
        verbose_name = "文档信息"
        verbose_name_plural = verbose_name
        ordering = ['title', 'version', 'date']

    def __str__(self):
        return self.title
        
        
## 添加监听器
@receiver(post_delete, sender=Document)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'file')
    #rint(str(files))
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)

    

    
    
    

 

    
    